package com.atguigu.daijia.rules.service.impl;

import com.atguigu.daijia.model.entity.rule.ProfitsharingRule;
import com.atguigu.daijia.model.form.rules.ProfitsharingRuleRequest;
import com.atguigu.daijia.model.form.rules.ProfitsharingRuleRequestForm;
import com.atguigu.daijia.model.vo.rules.ProfitsharingRuleResponse;
import com.atguigu.daijia.model.vo.rules.ProfitsharingRuleResponseVo;
import com.atguigu.daijia.rules.config.DroolsHelper;
import com.atguigu.daijia.rules.mapper.ProfitsharingRuleMapper;
import com.atguigu.daijia.rules.service.ProfitsharingRuleService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.kie.api.runtime.KieSession;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
@RequiredArgsConstructor
public class ProfitsharingRuleServiceImpl implements ProfitsharingRuleService {

    private final ProfitsharingRuleMapper profitsharingRuleMapper;

    /**
     * 计算分账信息
     * @param profitsharingRuleRequestForm
     * @return
     */
    @Override
    public ProfitsharingRuleResponseVo calculateOrderProfitsharingFee(ProfitsharingRuleRequestForm profitsharingRuleRequestForm) {
        // 封装规则引擎需要传入的参数
        ProfitsharingRuleRequest profitsharingRuleRequest = new ProfitsharingRuleRequest();
        BeanUtils.copyProperties(profitsharingRuleRequestForm, profitsharingRuleRequest);

        // 从数据库中获取最新的分账规则
        ProfitsharingRule profitsharingRule = profitsharingRuleMapper.selectOne(new LambdaQueryWrapper<ProfitsharingRule>()
                .orderByDesc(ProfitsharingRule::getId)
                .last("LIMIT 1"));
        // 加载规则
        KieSession kieSession = DroolsHelper.loadForRule(profitsharingRule.getRule());
        // 设置规则引擎全局变量，用于规则引擎计算后，返回结果
        ProfitsharingRuleResponse profitsharingRuleResponse = new ProfitsharingRuleResponse();
        kieSession.setGlobal("profitsharingRuleResponse", profitsharingRuleResponse);
        // 将参数传入规则引擎
        kieSession.insert(profitsharingRuleRequest);
        // 执行规则
        kieSession.fireAllRules();
        // 关闭会话
        kieSession.dispose();

        // 封装返回结果
        ProfitsharingRuleResponseVo profitsharingRuleResponseVo = new ProfitsharingRuleResponseVo();
        BeanUtils.copyProperties(profitsharingRuleResponse, profitsharingRuleResponseVo);
        profitsharingRuleResponseVo.setProfitsharingRuleId(profitsharingRule.getId());

        return profitsharingRuleResponseVo;
    }
}
